package luanvan.app.foodnote;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.slidingmenu.lib.SlidingMenu;
import com.slidingmenu.lib.app.SlidingActivityBase;


import luanvan.app.foodnote.library.AlertDialogManager;
import luanvan.app.foodnote.library.GooglePlaces;
import luanvan.app.foodnote.library.JSONParser;
import luanvan.app.foodnote.library.PlacesList;
import luanvan.app.foodnote.library.UserFunctions;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;

import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class AllFoodsActivity extends SherlockActivity {
	
	private ListView listFood;
	// ArrayList thats going to hold the search results
	ArrayList<HashMap<String, String>> searchResults;
	// ArrayList that will hold the original Data
	ArrayList<HashMap<String, String>> originalValues;

	CustomAdapter customAdapter;
	// Progress Dialog
	private ProgressDialog pDialog;

	// Creating JSON Parser object
	JSONParser jParser = new JSONParser();

	ArrayList<HashMap<String, String>> foodsList;
	// url to get all products list
	private static String url_foods_user = "http://192.168.0.129/foodnote/get_foods_user.php"; 
	private static String url_all_foods = "http://192.168.0.129/foodnote/get_all_foods.php";

	/*private static String url_foods_user = "http://10.0.2.2/foodnote/get_foods_user.php";
	private static String url_all_foods = "http://10.0.2.2/foodnote/get_all_foods.php";*/

	// JSON Node names
	private static final String TAG_SUCCESS = "success";
	private static final String TAG_FOODS = "foods";
	private static final String TAG_ID = "id";
	private static final String TAG_PLACE_NAME = "TEN_DIA_DIEM";
	private static final String TAG_NAME = "TEN_MON_AN";
	private static final String TAG_ADDRESS = "DIA_CHI";
	private static final String TAG_CITY = "THANH_PHO";

	private static final String TAG_LAT = "LATITUDE";
	private static final String TAG_LNG = "LONGITUDE";
	private static final String TAG_TYPE_FOOD_ID = "LOAI_MON_AN_id";

	// products JSONArray
	JSONArray foods = null;

	String fid, lat, lng;

	AlertDialogManager alert = new AlertDialogManager();

	// Google Places
	GooglePlaces googlePlaces;

	// Places List
	PlacesList nearPlaces;

	boolean flagPref = false;

	SimpleAdapter adapter;

	// Edit search
	EditText inputSearch;
	LayoutInflater inflater;
    
    // Search options
    int searchOptions = 1;
	private OnClickListener lis = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			Toast.makeText(getApplicationContext(), "aaaaaaaaaa", Toast.LENGTH_LONG).show();
			
		}
	};
	private TextWatcher textWatcher = new TextWatcher() {
		
		@Override
		public void onTextChanged(CharSequence cs, int start, int before,
				int count) {
			String searchString = inputSearch.getText().toString();
			int textLength = searchString.length();
			searchResults.clear();
			for(int i = 0; i < originalValues.size(); i++){
				String foodName;
				if(searchOptions ==  1){
					foodName = originalValues.get(i).get(TAG_NAME).toString();
					if(textLength <= foodName.length()){
						//compare the String in EditText with Names in the ArrayList
						if(searchString.equalsIgnoreCase(foodName.substring(0, textLength)))
							searchResults.add(originalValues.get(i));
					}
				} else if(searchOptions == 2){
					foodName = originalValues.get(i).get(TAG_ADDRESS).toString();
					if(textLength <= foodName.length()){
						//compare the String in EditText with Names in the ArrayList
						if(searchString.equalsIgnoreCase(foodName.substring(0, textLength)))
							searchResults.add(originalValues.get(i));
					}
				} else if(searchOptions == 3){
					foodName = originalValues.get(i).get(TAG_CITY).toString();
					if(textLength <= foodName.length()){
						//compare the String in EditText with Names in the ArrayList
						if(searchString.equalsIgnoreCase(foodName.substring(0, textLength)))
							searchResults.add(originalValues.get(i));
					}
				}
			}
			//adapter.getFilter().filter(cs.toString());
			customAdapter.notifyDataSetChanged();
		}
		
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void afterTextChanged(Editable s) {
			// TODO Auto-generated method stub
			
		}
	};
	@Override
	public void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_LEFT_ICON);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.form_places);
		getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
				R.drawable.food_list);
        
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		getSupportActionBar().setDisplayShowHomeEnabled(true);
		getSupportActionBar().setDisplayShowTitleEnabled(true);
		getSupportActionBar().setIcon(getResources().getDrawable(R.drawable.food_list));
		getSupportActionBar().show();
		
		SlidingMenu menu;
	    menu = new SlidingMenu(this);
	    menu.setMode(SlidingMenu.LEFT);
	    menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
	    menu.setShadowWidth(5);
	    menu.setFadeDegree(0.0f);
	    menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
	    //menu.setBehindWidth(100);
	    menu.setBehindOffset(100);
	    menu.setMenu(R.layout.activity_rightmenu);
	    
	    findViewById(R.id.txtSlide).setOnClickListener(lis);
	        
		listFood = (ListView) findViewById(R.id.listFood);
		listFood.setCacheColorHint(Color.TRANSPARENT);
		
		inputSearch = (EditText) findViewById(R.id.inputSearch);
		
		inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		
		originalValues=new ArrayList<HashMap<String,String>>();
		
		new LoadFoodUser().execute();
		
		// register Context Menu
		registerForContextMenu(listFood);
		
		listFood.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				fid = ((TextView) view.findViewById(R.id.fid)).getText()
						.toString();
				lat = ((TextView) view.findViewById(R.id.lat)).getText()
						.toString();
				lng = ((TextView) view.findViewById(R.id.lng)).getText()
						.toString();
				// showDialog(CONTEXT_MENU_ID);
				openContextMenu(view);
			}
		});
	
		// Search food
		inputSearch.addTextChangedListener(textWatcher);
		
	}


	// Response from Edit Product Activity
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		// if result code 100
		if (resultCode == 100) {
			// if result code 100 is received
			// means user edited/deleted product
			// reload this screen again
			Intent intent = getIntent();
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			finish();
			startActivity(intent);
		} else if (requestCode == 101) {
			if (getListPrefValues().equals("1")) {
				originalValues.clear();
				new LoadFoodUser().execute();
			} else if (getListPrefValues().equals("2")) {
				originalValues.clear();
				new LoadAllFoods().execute();
			}
		}

	}

	class LoadFoodUser extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(AllFoodsActivity.this);
			// pDialog.setIcon(R.drawable.help);
			pDialog.setTitle("Please wait");
			pDialog.setMessage("Đang tải danh sách ...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		@Override
		protected String doInBackground(String... args) {

			UserFunctions userFunction = new UserFunctions();
			String uid = userFunction.getUID(getApplicationContext());

			// Building Parameters
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("uid", uid));
			// getting JSON string from URL
			JSONObject json = jParser.makeHttpRequest(url_foods_user, "POST",
					params);
			// Check your log cat for JSON reponse
			Log.d("All Foods: ", json.toString());

			try {
				// Checking for SUCCESS TAG
				int success = json.getInt(TAG_SUCCESS);

				if (success == 1) {
					foods = json.getJSONArray(TAG_FOODS);
					for (int i = 0; i < foods.length(); i++) {
						JSONObject c = foods.getJSONObject(i);

						// Storing each json item in variable
						String id = c.getString(TAG_ID);
						String placename = c.getString(TAG_PLACE_NAME);
						String name = c.getString(TAG_NAME);
						String city = c.getString(TAG_CITY);
						String address = c.getString(TAG_ADDRESS);
						String lat = c.getString(TAG_LAT);
						String lng = c.getString(TAG_LNG);
						String type_food_id = c.getString(TAG_TYPE_FOOD_ID);

						HashMap<String, String> map = new HashMap<String, String>();

						// adding each child node to HashMap key => value
						map.put(TAG_ID, id);
						map.put(TAG_LAT, lat);
						map.put(TAG_LNG, lng);
						map.put(TAG_PLACE_NAME, placename);
						map.put(TAG_NAME, name);
						map.put(TAG_CITY, city);
						map.put(TAG_ADDRESS, address);
						map.put(TAG_TYPE_FOOD_ID, type_food_id);

						// adding HashList to ArrayList
						//foodsList.add(map);
						
						originalValues.add(map);
						
					}
					searchResults = new ArrayList<HashMap<String,String>>(originalValues);
				} else {
					// no products found
					// Launch Add New product Activity
					/*
					 * Intent i = new Intent(getApplicationContext(),
					 * NewProductActivity.class); // Closing all previous
					 * activities i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					 * startActivity(i);
					 */
				}

			} catch (JSONException e) {
				e.printStackTrace();
			}
			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			pDialog.dismiss();
			
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					/**
					 * Updating parsed JSON data into ListView
					 * */
					/*adapter = new SimpleAdapter(AllFoodsActivity.this,
							foodsList, R.layout.row, new String[] { TAG_ID,
									TAG_LAT, TAG_LNG, TAG_PLACE_NAME, TAG_NAME,
									TAG_ADDRESS }, new int[] { R.id.fid,
									R.id.lat, R.id.lng, R.id.placename,
									R.id.foodname, R.id.address });*/
					
					customAdapter = new CustomAdapter(getApplicationContext(), R.layout.row, searchResults);
					// updating listview
					listFood.setAdapter(customAdapter);

				}
			});
		}

	}

	class LoadAllFoods extends AsyncTask<String, String, String> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(AllFoodsActivity.this);
			pDialog.setTitle("Please wait");
			pDialog.setMessage("Đang tải danh sách ...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		@Override
		protected String doInBackground(String... agrs) {

			List<NameValuePair> params = new ArrayList<NameValuePair>();
			// getting JSON string from URL
			JSONObject json = jParser.makeHttpRequest(url_all_foods, "GET",
					params);
			// Check your log cat for JSON reponse
			Log.d("All Foods: ", json.toString());

			try {
				// Checking for SUCCESS TAG
				int success = json.getInt(TAG_SUCCESS);

				if (success == 1) {
					foods = json.getJSONArray(TAG_FOODS);
					for (int i = 0; i < foods.length(); i++) {
						JSONObject c = foods.getJSONObject(i);

						// Storing each json item in variable
						String id = c.getString(TAG_ID);
						String placename = c.getString(TAG_PLACE_NAME);
						String name = c.getString(TAG_NAME);
						String city = c.getString(TAG_CITY);
						String address = c.getString(TAG_ADDRESS);
						String lat = c.getString(TAG_LAT);
						String lng = c.getString(TAG_LNG);
						String type_food_id = c.getString(TAG_TYPE_FOOD_ID);

						HashMap<String, String> map = new HashMap<String, String>();

						// adding each child node to HashMap key => value
						map.put(TAG_ID, id);
						map.put(TAG_LAT, lat);
						map.put(TAG_LNG, lng);
						map.put(TAG_PLACE_NAME, placename);
						map.put(TAG_NAME, name);
						map.put(TAG_CITY, city);
						map.put(TAG_ADDRESS, address);
						map.put(TAG_TYPE_FOOD_ID, type_food_id);

						// adding HashList to ArrayList
						//foodsList.add(map);
						originalValues.add(map);
					}
					searchResults = new ArrayList<HashMap<String,String>>(originalValues);
				} else {
					// no products found
					// Launch Add New product Activity
					/*
					 * Intent i = new Intent(getApplicationContext(),
					 * NewProductActivity.class); // Closing all previous
					 * activities i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					 * startActivity(i);
					 */
				}

			} catch (JSONException e) {
				e.printStackTrace();
			}
			return null;
		}

		protected void onPostExecute(String file_url) {
			pDialog.dismiss();
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					/**
					 * Updating parsed JSON data into ListView
					 * */
					/*adapter = new SimpleAdapter(AllFoodsActivity.this,
							foodsList, R.layout.row, new String[] { TAG_ID,
									TAG_LAT, TAG_LNG, TAG_PLACE_NAME, TAG_NAME,
									TAG_ADDRESS }, new int[] { R.id.fid,
									R.id.lat, R.id.lng, R.id.placename,
									R.id.foodname, R.id.address });*/
					// updating listview
					customAdapter = new CustomAdapter(getApplicationContext(), R.layout.row, searchResults);
					// updating listview
					listFood.setAdapter(customAdapter);
					//setListAdapter(adapter);

				}
			});
		}
	}

	@Override
	protected void onResume() {
		super.onResume();

	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.setHeaderTitle("Tùy chọn");
		menu.setHeaderIcon(R.drawable.submenu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.context_menu, menu);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();
		Long id = listFood.getItemIdAtPosition(info.position);
		//Long id = getListAdpter.getItemId(info.position);
		Log.d("id = ", String.valueOf(id));
		switch (item.getItemId()) {
		case R.id.update:
			Intent intentFoodPlace = new Intent(AllFoodsActivity.this,
					EditFoodActivity.class);
			intentFoodPlace.putExtra(TAG_ID, fid);
			Log.d("FOOD_ID", fid);
			startActivityForResult(intentFoodPlace, 100);
			return true;

		case R.id.food_places:
			Intent googlePlaces = new Intent(AllFoodsActivity.this,
					GooglePlacesActivity.class);
			googlePlaces.putExtra(TAG_LAT, Double.valueOf(lat));
			googlePlaces.putExtra(TAG_LNG, Double.valueOf(lng));
			startActivity(googlePlaces);
			return true;

		case R.id.direction:
			Intent direction = new Intent(AllFoodsActivity.this,
					DirectionsActivity.class);
			direction.putExtra(TAG_LAT, Double.valueOf(lat));
			direction.putExtra(TAG_LNG, Double.valueOf(lng));
			startActivity(direction);
			return true;

		}
		return (super.onOptionsItemSelected(item));
	}

	 /** Callback function */
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.menu, menu);
		/*final EditText search = (EditText) menu.findItem(R.id.menu_search).getActionView();
		search.addTextChangedListener(textWatcher);*/
		
        return super.onCreateOptionsMenu(menu);
	}
	@Override
	public boolean onOptionsItemSelected(com.actionbarsherlock.view.MenuItem item) {
	    switch(item.getItemId()){
	    case R.id.addFood:
	    	startActivity(new Intent(AllFoodsActivity.this, NewFoodActivity.class));
	        return true;
	    case R.id.showListFood:
	    	Intent i = new Intent(AllFoodsActivity.this, ShowSettingActivity.class);
	    	startActivityForResult(i, 101);
	    	return true;
	    case R.id.searchName:
	    	//Toast.makeText(getApplicationContext(), "Chọn tìm tên món ăn", Toast.LENGTH_SHORT);
	    	Log.d("Search Options", "Seach name");
	    	searchOptions = 1;
	    	return true;
	    	
	    case R.id.seachAddress:
	    	//Toast.makeText(getApplicationContext(), "Chọn tìm địa chỉ món ăn", Toast.LENGTH_SHORT);
	    	Log.d("Search Options", "Seach address");
	    	searchOptions = 2;
	    	return true;
	    case R.id.searchCity:
	    	searchOptions = 3;
	    	return true;
	    	
	    case R.id.quitFood:
	    	UserFunctions user = new UserFunctions();
	    	user.logoutUser(getApplicationContext());
	    	Intent login = new Intent(getApplicationContext(), LoginActivity.class);
			login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(login);
            // Closing dashboard screen
            finish();
	    	return true;
	        
	    }
	    return false;
	}
	
	/**
	 * Setting show list view
	 * 
	 * @return
	 */
	private String getListPrefValues() {
		SharedPreferences settings = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());
		String listPrefValues = settings.getString("showlist", "1");
		return listPrefValues;
	}

	private class CustomAdapter extends ArrayAdapter<HashMap<String, String>> {
		ArrayList<HashMap<String, String>> posters;
		public CustomAdapter(Context context, int textViewResourceId,
				ArrayList<HashMap<String, String>> objects) {
			super(context, textViewResourceId, objects);
			// TODO Auto-generated constructor stub
			posters = objects;
		}

		@Override
		public int getCount(){ 
			return posters!=null ? posters.size() : 0;
		}
		// class for caching the view in a row
		private class ViewHolder {
			TextView id, lat, lng, city, type_food_id, food_name, place_name, food_address;
			ImageView icon;
		}

		ViewHolder viewHolder;

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.row, null);
				viewHolder = new ViewHolder();

				// cache the views
				viewHolder.icon = (ImageView) convertView.findViewById(R.id.icon);
				viewHolder.id = (TextView) convertView.findViewById(R.id.fid);
				viewHolder.lat = (TextView) convertView.findViewById(R.id.lat);
				viewHolder.lng = (TextView) convertView.findViewById(R.id.lng);
				viewHolder.city = (TextView) convertView.findViewById(R.id.city);
				viewHolder.type_food_id = (TextView) convertView.findViewById(R.id.type_food_id);
				viewHolder.food_name = (TextView) convertView.findViewById(R.id.foodname);
				viewHolder.place_name = (TextView) convertView.findViewById(R.id.placename);
				viewHolder.food_address = (TextView) convertView.findViewById(R.id.address);
				
				// link the cached views to the convertview
				convertView.setTag(viewHolder);
			} else
				viewHolder = (ViewHolder) convertView.getTag();

			// set the data to be displayed
			viewHolder.id.setText(searchResults.get(position).get(TAG_ID).toString());
			
			viewHolder.lat.setText(searchResults.get(position).get(TAG_LAT).toString());
			
			viewHolder.lng.setText(searchResults.get(position).get(TAG_LNG).toString());
			
			viewHolder.city.setText(searchResults.get(position).get(TAG_CITY).toString());
			
			viewHolder.type_food_id.setText(searchResults.get(position).get(TAG_TYPE_FOOD_ID).toString());
			
			viewHolder.food_name.setText(searchResults.get(position).get(TAG_NAME).toString());
			
			viewHolder.place_name.setText(searchResults.get(position).get(TAG_PLACE_NAME).toString());
			
			viewHolder.food_address.setText(searchResults.get(position).get(TAG_ADDRESS).toString());
			
			if(Integer.valueOf(searchResults.get(position).get(TAG_TYPE_FOOD_ID).toString()) == 1){
				viewHolder.icon.setImageResource(R.drawable.icon_fast_food);
			} else if(Integer.valueOf(searchResults.get(position).get(TAG_TYPE_FOOD_ID).toString()) == 2){
				viewHolder.icon.setImageResource(R.drawable.dessert);
			} else if(Integer.valueOf(searchResults.get(position).get(TAG_TYPE_FOOD_ID).toString()) == 3){
				viewHolder.icon.setImageResource(R.drawable.drink_icon);
			}

			return convertView;
		}
	}

}
